import { useState, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Card, Table, Input, Button, Space, Modal, Form, message, Tag, Popconfirm, Tabs, InputNumber } from 'antd';
import { SearchOutlined, EditOutlined, DeleteOutlined, UserOutlined, TeamOutlined } from '@ant-design/icons';
import { getAllStudents, getAllTeachers, updateStudent, updateTeacher, deleteStudent, deleteTeacher } from '../../api/admin';
import type { Student, Teacher } from '../../types';

export default function Users() {
  const queryClient = useQueryClient();
  const [studentSearchText, setStudentSearchText] = useState('');
  const [teacherSearchText, setTeacherSearchText] = useState('');
  const [selectedStudent, setSelectedStudent] = useState<Student | null>(null);
  const [selectedTeacher, setSelectedTeacher] = useState<Teacher | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [editRole, setEditRole] = useState<'student' | 'teacher'>('student');
  const [form] = Form.useForm();

  // 获取学生列表
  const { data: students = [], isLoading: studentsLoading } = useQuery({
    queryKey: ['admin', 'students'],
    queryFn: getAllStudents,
  });

  // 获取教师列表
  const { data: teachers = [], isLoading: teachersLoading } = useQuery({
    queryKey: ['admin', 'teachers'],
    queryFn: getAllTeachers,
  });

  // 过滤学生列表
  const filteredStudents = useMemo(() => {
    if (!studentSearchText.trim()) {
      return students;
    }
    const lowerSearch = studentSearchText.toLowerCase();
    return students.filter(student => 
      student.name.toLowerCase().includes(lowerSearch) ||
      student.studentNo.toLowerCase().includes(lowerSearch) ||
      student.college?.toLowerCase().includes(lowerSearch) ||
      student.major?.toLowerCase().includes(lowerSearch) ||
      student.clazz?.toLowerCase().includes(lowerSearch)
    );
  }, [students, studentSearchText]);

  // 过滤教师列表
  const filteredTeachers = useMemo(() => {
    if (!teacherSearchText.trim()) {
      return teachers;
    }
    const lowerSearch = teacherSearchText.toLowerCase();
    return teachers.filter(teacher => 
      teacher.name.toLowerCase().includes(lowerSearch) ||
      teacher.account.toLowerCase().includes(lowerSearch) ||
      teacher.college?.toLowerCase().includes(lowerSearch) ||
      teacher.title?.toLowerCase().includes(lowerSearch)
    );
  }, [teachers, teacherSearchText]);

  // 更新学生Mutation
  const updateStudentMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<Student> }) => updateStudent(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'students'] });
      message.success('学生信息更新成功');
      setIsEditModalOpen(false);
      setSelectedStudent(null);
      form.resetFields();
    },
    onError: (error: any) => {
      message.error(error.message || '更新失败，请重试');
    },
  });

  // 更新教师Mutation
  const updateTeacherMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<Teacher> }) => updateTeacher(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'teachers'] });
      message.success('教师信息更新成功');
      setIsEditModalOpen(false);
      setSelectedTeacher(null);
      form.resetFields();
    },
    onError: (error: any) => {
      message.error(error.message || '更新失败，请重试');
    },
  });

  // 删除学生Mutation
  const deleteStudentMutation = useMutation({
    mutationFn: deleteStudent,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'students'] });
      message.success('学生删除成功');
    },
    onError: (error: any) => {
      message.error(error.message || '删除失败，请重试');
    },
  });

  // 删除教师Mutation
  const deleteTeacherMutation = useMutation({
    mutationFn: deleteTeacher,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin', 'teachers'] });
      message.success('教师删除成功');
    },
    onError: (error: any) => {
      message.error(error.message || '删除失败，请重试');
    },
  });

  const handleViewStudent = (student: Student) => {
    setSelectedStudent(student);
    setEditRole('student');
    // 确保所有字段都能正确回显，如果数据库没有则留空
    // 使用 ?? 来处理 null 和 undefined，使用 || 来处理空字符串
    const formValues = {
      name: student.name ?? '',
      studentNo: student.studentNo ?? '',
      college: student.college ?? '',
      major: student.major ?? '',
      clazz: student.clazz ?? '',
      grade: student.grade ?? '',
      email: student.email ?? '',
      phone: student.phone ?? '',
    };
    form.setFieldsValue(formValues);
    setIsEditModalOpen(true);
  };

  const handleViewTeacher = (teacher: Teacher) => {
    setSelectedTeacher(teacher);
    setEditRole('teacher');
    // 确保所有字段都能正确回显，如果数据库没有则留空
    // 使用 ?? 来处理 null 和 undefined，使用 || 来处理空字符串
    const formValues = {
      name: teacher.name ?? '',
      account: teacher.account ?? '',
      college: teacher.college ?? '',
      title: teacher.title ?? '',
      email: teacher.email ?? '',
      phone: teacher.phone ?? '',
      researchArea: teacher.researchArea ?? '',
      publishedPapers: teacher.publishedPapers ?? 0,
      intro: teacher.intro ?? '',
    };
    form.setFieldsValue(formValues);
    setIsEditModalOpen(true);
  };

  const handleEditSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editRole === 'student' && selectedStudent) {
        // 后端UpdateStudentsRequest只支持：name, major, clazz
        updateStudentMutation.mutate({
          id: selectedStudent.id,
          data: {
            name: values.name,
            major: values.major,
            clazz: values.clazz,
          },
        });
      } else if (editRole === 'teacher' && selectedTeacher) {
        // 后端UpdateTeachersRequest只支持：name, title
        updateTeacherMutation.mutate({
          id: selectedTeacher.id,
          data: {
            name: values.name,
            title: values.title,
          },
        });
      }
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const studentColumns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      render: (text: string, record: Student) => (
        <Button type="link" onClick={() => handleViewStudent(record)} style={{ padding: 0 }}>
          {text}
        </Button>
      ),
    },
    {
      title: '学号',
      dataIndex: 'studentNo',
      key: 'studentNo',
      width: 120,
    },
    {
      title: '所属学院',
      dataIndex: 'college',
      key: 'college',
      width: 180,
    },
    {
      title: '专业',
      dataIndex: 'major',
      key: 'major',
      width: 150,
    },
    {
      title: '班级',
      dataIndex: 'clazz',
      key: 'clazz',
      width: 120,
    },
    {
      title: '年级',
      dataIndex: 'grade',
      key: 'grade',
      width: 100,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: Student) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleViewStudent(record)}
            size="small"
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除该学生吗？"
            description="删除后将无法恢复"
            onConfirm={() => deleteStudentMutation.mutate(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const teacherColumns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      render: (text: string, record: Teacher) => (
        <Button type="link" onClick={() => handleViewTeacher(record)} style={{ padding: 0 }}>
          {text}
        </Button>
      ),
    },
    {
      title: '工号',
      dataIndex: 'account',
      key: 'account',
      width: 120,
    },
    {
      title: '所属学院',
      dataIndex: 'college',
      key: 'college',
      width: 180,
    },
    {
      title: '职称',
      dataIndex: 'title',
      key: 'title',
      width: 100,
    },
    {
      title: '研究方向',
      dataIndex: 'researchArea',
      key: 'researchArea',
      width: 200,
      ellipsis: true,
    },
    {
      title: '发表论文数',
      dataIndex: 'publishedPapers',
      key: 'publishedPapers',
      width: 100,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: Teacher) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleViewTeacher(record)}
            size="small"
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除该教师吗？"
            description="删除后将无法恢复"
            onConfirm={() => deleteTeacherMutation.mutate(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="p-4 pb-24">
      <div className="text-2xl font-semibold mb-4">用户管理</div>

      <Card>
        <Tabs
          defaultActiveKey="students"
          items={[
            {
              key: 'students',
              label: (
                <span>
                  <UserOutlined className="mr-2" />
                  学生管理 ({filteredStudents.length})
                </span>
              ),
              children: (
                <div>
                  <div className="mb-4">
                    <Input
                      placeholder="搜索学生（姓名、学号、学院、专业、班级）"
                      prefix={<SearchOutlined />}
                      value={studentSearchText}
                      onChange={(e) => setStudentSearchText(e.target.value)}
                      allowClear
                      style={{ maxWidth: 400 }}
                    />
                  </div>
                  <Table
                    dataSource={filteredStudents}
                    columns={studentColumns}
                    rowKey="id"
                    loading={studentsLoading}
                    pagination={{
                      pageSize: 10,
                      showSizeChanger: true,
                      showTotal: (total) => `共 ${total} 条`,
                    }}
                    locale={{
                      emptyText: '暂无学生',
                    }}
                  />
                </div>
              ),
            },
            {
              key: 'teachers',
              label: (
                <span>
                  <TeamOutlined className="mr-2" />
                  教师管理 ({filteredTeachers.length})
                </span>
              ),
              children: (
                <div>
                  <div className="mb-4">
                    <Input
                      placeholder="搜索教师（姓名、工号、学院、职称）"
                      prefix={<SearchOutlined />}
                      value={teacherSearchText}
                      onChange={(e) => setTeacherSearchText(e.target.value)}
                      allowClear
                      style={{ maxWidth: 400 }}
                    />
                  </div>
                  <Table
                    dataSource={filteredTeachers}
                    columns={teacherColumns}
                    rowKey="id"
                    loading={teachersLoading}
                    pagination={{
                      pageSize: 10,
                      showSizeChanger: true,
                      showTotal: (total) => `共 ${total} 条`,
                    }}
                    locale={{
                      emptyText: '暂无教师',
                    }}
                  />
                </div>
              ),
            },
          ]}
        />
      </Card>

      {/* 编辑/查看详情Modal */}
      <Modal
        title={editRole === 'student' ? '学生信息' : '教师信息'}
        open={isEditModalOpen}
        onCancel={() => {
          setIsEditModalOpen(false);
          setSelectedStudent(null);
          setSelectedTeacher(null);
          form.resetFields();
        }}
        onOk={handleEditSubmit}
        confirmLoading={updateStudentMutation.isPending || updateTeacherMutation.isPending}
        okText="保存"
        cancelText="取消"
        width={700}
      >
        <Form
          form={form}
          layout="vertical"
          className="mt-4"
        >
          {editRole === 'student' ? (
            <>
              <div className="grid grid-cols-2 gap-4">
                <Form.Item
                  label="姓名"
                  name="name"
                  rules={[{ required: true, message: '请输入姓名' }]}
                >
                  <Input placeholder="请输入姓名" />
                </Form.Item>
                <Form.Item
                  label="学号"
                  name="studentNo"
                  rules={[{ required: true, message: '请输入学号' }]}
                >
                  <Input placeholder="请输入学号" disabled />
                </Form.Item>
                <Form.Item
                  label="所属学院"
                  name="college"
                  rules={[{ required: true, message: '请输入所属学院' }]}
                >
                  <Input placeholder="请输入所属学院" />
                </Form.Item>
                <Form.Item
                  label="专业"
                  name="major"
                  rules={[{ required: true, message: '请输入专业' }]}
                >
                  <Input placeholder="请输入专业" />
                </Form.Item>
                <Form.Item
                  label="班级"
                  name="clazz"
                  rules={[{ required: true, message: '请输入班级' }]}
                >
                  <Input placeholder="请输入班级" />
                </Form.Item>
                <Form.Item
                  label="年级"
                  name="grade"
                >
                  <Input placeholder="例如：2021级（可选）" />
                </Form.Item>
                <Form.Item
                  label="邮箱"
                  name="email"
                  rules={[{ type: 'email', message: '请输入有效的邮箱地址' }]}
                >
                  <Input placeholder="请输入邮箱（可选）" />
                </Form.Item>
                <Form.Item
                  label="联系电话"
                  name="phone"
                  rules={[{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }]}
                >
                  <Input placeholder="请输入联系电话（可选）" />
                </Form.Item>
              </div>
            </>
          ) : (
            <>
              <div className="grid grid-cols-2 gap-4">
                <Form.Item
                  label="姓名"
                  name="name"
                  rules={[{ required: true, message: '请输入姓名' }]}
                >
                  <Input placeholder="请输入姓名" />
                </Form.Item>
                <Form.Item
                  label="工号"
                  name="account"
                  rules={[{ required: true, message: '请输入工号' }]}
                >
                  <Input placeholder="请输入工号" disabled />
                </Form.Item>
                <Form.Item
                  label="所属学院"
                  name="college"
                  rules={[{ required: true, message: '请输入所属学院' }]}
                >
                  <Input placeholder="请输入所属学院" />
                </Form.Item>
                <Form.Item
                  label="职称"
                  name="title"
                  rules={[{ required: true, message: '请输入职称' }]}
                >
                  <Input placeholder="例如：教授、副教授、讲师" />
                </Form.Item>
                <Form.Item
                  label="邮箱"
                  name="email"
                  rules={[{ type: 'email', message: '请输入有效的邮箱地址' }]}
                  className="col-span-2"
                >
                  <Input placeholder="请输入邮箱（可选）" />
                </Form.Item>
                <Form.Item
                  label="联系电话"
                  name="phone"
                  rules={[{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }]}
                  className="col-span-2"
                >
                  <Input placeholder="请输入联系电话（可选）" />
                </Form.Item>
                <Form.Item
                  label="研究方向"
                  name="researchArea"
                  className="col-span-2"
                >
                  <Input.TextArea 
                    placeholder="请输入研究方向（可选）"
                    rows={3}
                    showCount
                    maxLength={200}
                  />
                </Form.Item>
                <Form.Item
                  label="发表论文数"
                  name="publishedPapers"
                  rules={[{ type: 'number', min: 0, message: '论文数不能为负数' }]}
                >
                  <InputNumber 
                    placeholder="请输入发表论文数（可选）"
                    min={0}
                    className="w-full"
                    style={{ width: '100%' }}
                  />
                </Form.Item>
                <Form.Item
                  label="简介"
                  name="intro"
                  className="col-span-2"
                >
                  <Input.TextArea 
                    placeholder="请输入教师简介（可选）"
                    rows={3}
                    showCount
                    maxLength={500}
                  />
                </Form.Item>
              </div>
            </>
          )}
        </Form>
      </Modal>
    </div>
  );
}
